﻿using System.Security.Claims;
using Furion;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using PMBF.Core.Managers;
using Furion.FriendlyException;
using PMBF.Core.Enums;
using PMBF.Core.Handler;
using DB.Core.Models;
using PMBF.Core.ViewModels;
using System;

namespace PMBF.Application.Api
{
    /// <summary>
    /// API DEMO 
    /// </summary>
    [AppAuthorize, ApiDescriptionSettings("DEMO列表@1")]
    [UserApiAuthenticationActionFilter]
    public class DemoService : IDynamicApiController
    {
        private readonly ISqlSugarRepository repository;
        private readonly SqlSugarClient db;
        private readonly int ModelId = 14;

        public DemoService(ISqlSugarRepository sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            db = repository.Context;

            //配置用户角色
            //db.ConfigQuery.SetTable<SysRole>(it => it.Id, it => it.Name);

        }

        /// <summary>
        /// 测试API Demo
        /// </summary>
        /// <returns></returns>
        /// //自定义过滤器"自定义资源ID"
        [SecurityDefine(CoreSecurityAttribute.ViewRoles)]
        public string GetDemo()
        {
            //获取登录时生成的jwt token中的数据
            var userId = App.User?.FindFirstValue("UserID");
            return "hello world ：" + userId;
        }

        [AllowAnonymous]
        public string GetSomeInfo()
        {
            throw Oops.Oh(SystemErrorCodes.E0003);
        }

        [AllowAnonymous]
        public string GetFilterCs()
        {
            return "ce";
        }

        #region 查询列表、编辑、保存、禁用、删除、导出

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="_query"></param>
        /// <returns></returns>
        public Model Post(ApiModelsQuerys _query)
        {
            return new ModelsService(repository).Model(ModelId, _query);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="_query"></param>
        /// <returns></returns>
        [NonUnify]
        public IActionResult PostExport(ApiModelsQuerys _query)
        {
            return new ModelsService(repository).Export(ModelId, _query);
        }

        /// <summary>
        /// 新增编辑，获取信息
        /// </summary>
        /// <param name="_id"></param>
        /// <returns></returns>
        public dynamic GetInfo(int _id)
        {
            var page = new ModelsService(repository).GetEditData(ModelId);

            if (_id != 0)
            {
                page.Page.Title = "编辑Demo";
                page.DataSource = db.Queryable<Demo>().Where(n => n.ID == _id).First();
            }
            else
            {
                page.Page.Title = "新增Demo";
                //page.DataSource = db.Queryable<Demo>().Where(n => n.ID == _id).First();
            }

            return page;
        }

        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public dynamic PostSave(Demo model)
        {
            bool isok = false;

            if (model.ID == 0)
            {
                model.ModifyTime = DateTime.Now;
                model.ModifyUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                model.CreateTime = DateTime.Now;
                model.CreateUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                model.DeleteFlag = 0;
                isok = db.Insertable(model).ExecuteCommand() > 0;
            }
            else
            {
                model.ModifyTime = DateTime.Now;
                model.ModifyUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                isok = db.Updateable(model).IgnoreColumns(ignoreAllNullColumns: true).IgnoreColumns("CreateTime", "CreateUserID").ExecuteCommand() > 0;
            }

            if (isok == false)
            {
                throw Oops.Oh(SystemErrorCodes.E0010);
            }

            return new { Success = true, message = "保存成功" };
        }


        /// <summary>
        /// 正常数据，将数据删除标志设置成已删除
        /// </summary>
        /// <returns></returns>
        public dynamic PostDisable(ApiPostExtendModel data)
        {
            int userId = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
            foreach (int id in data.ids)
            {
                db.Updateable<Demo>().SetColumns(n => new Demo()
                {
                    DeleteFlag = 1,
                    DeleteTime = DateTime.Now,
                    DeleteUserID = userId

                }).Where(n => n.ID == id).ExecuteCommand();
            }

            return new { Success = true, message = "删除成功" };
        }


        /// <summary>
        /// 有数据删除标志设置的直接删除
        /// </summary>
        /// <returns></returns>
        public dynamic PostDelete(ApiPostExtendModel data)
        {
            foreach (int id in data.ids)
            {
                db.Deleteable<Demo>().Where(n => n.ID == id && n.DeleteFlag == 1).ExecuteCommand();
            }

            return new { Success = true, message = "删除成功" };
        }

        /// <summary>
        /// 有数据删除标志设置的恢复
        /// </summary>
        /// <returns></returns>
        public dynamic PostRestore(ApiPostExtendModel data)
        {
            int userId = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
            foreach (int id in data.ids)
            {
                db.Updateable<Demo>().SetColumns(n => new Demo() { DeleteFlag = 0, ModifyTime = DateTime.Now, ModifyUserID = userId }).Where(n => n.ID == id && n.DeleteFlag == 1).ExecuteCommand();
            }

            return new { Success = true, message = "恢复成功" };
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <returns></returns>
        public dynamic PostAudit(ApiPostExtendModel data)
        {
            return new { Success = true, message = "审核成功" };
        }
        #endregion
    }
}
